package org.jeecg.modules.online.desform.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.modules.online.desform.constant.PermissionTypeEnum;
import org.jeecg.modules.online.desform.entity.DesignFormAuth;
import org.jeecg.modules.online.desform.service.IDesignFormAuthService;
import org.jeecg.modules.online.desform.service.IDesignFormService;
import org.jeecg.modules.online.desform.util.DesformAuthUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;

/**
 * @Description: 表单设计器字段权限表
 * @Author: jeecg-boot
 * @Date: 2019-09-03
 * @Version: V1.0
 */
@Slf4j
@Api(tags = "表单设计器字段权限表")
@RestController("designFormAuthController")
@RequestMapping("/desform/auth")
public class DesignFormAuthController {

    @Autowired
    private IDesignFormAuthService designFormAuthService;

    @Autowired
    private IDesignFormService designFormService;

    /**
     * 全局异常捕获
     */
    @ExceptionHandler(Exception.class)
    public Result<?> ta(Exception exception) {
        try {
            throw exception;
        } catch (JeecgBootException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    /**
     * 分页列表查询
     *
     * @param designFormAuth
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @GetMapping(value = "/list")
    public Result<IPage<DesignFormAuth>> queryPageList(
            DesignFormAuth designFormAuth,
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            HttpServletRequest req
    ) {
        Result<IPage<DesignFormAuth>> result = new Result<IPage<DesignFormAuth>>();
        QueryWrapper<DesignFormAuth> queryWrapper = QueryGenerator.initQueryWrapper(designFormAuth, req.getParameterMap());
        Page<DesignFormAuth> page = new Page<DesignFormAuth>(pageNo, pageSize);
        IPage<DesignFormAuth> pageList = designFormAuthService.page(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    /**
     * 根据 token 查询用户信息以及所拥有的部门
     *
     * @param token
     * @return
     */
    @GetMapping(value = "/queryUserByToken")
    public Result<?> queryUserByToken(@RequestParam(name = "token") String token) {
        String username = JwtUtil.getUsername(token);
        return this.queryUser(username);
    }

    /**
     * 根据 username 查询用户信息以及所拥有的部门
     *
     * @param username
     * @return
     */
    @GetMapping(value = "/queryUser/{username}")
    public Result<?> queryUser(@PathVariable("username") String username) {
        return Result.ok(designFormAuthService.getUserInfoByUsername(username));
    }

    /**
     * 根据 desformCode 查询所有权限
     *
     * @param desformCode
     * @param taskId
     * @param group       是否合并数据（默认返回两条数据，合并后只返回 authType=1 的一条数据
     * @return
     */
    @GetMapping(value = "/query/{code}")
    public Result<?> queryByCode(
            @PathVariable("code") String desformCode,
            @RequestParam(name = "taskId", required = false) String taskId,
            @RequestParam(name = "group", required = false, defaultValue = "false") Boolean group
    ) {
        if (StringUtils.isEmpty(taskId)) {
            return Result.ok(designFormAuthService.queryByCode(desformCode, group));
        } else {
            return Result.ok(designFormAuthService.queryByTaskId(desformCode, taskId));
        }
    }

    /**
     * 根据 desformCode 和 authComKey 查询单个权限
     *
     * @param desformCode
     * @return
     */
    @GetMapping(value = "/query/{desformCode}/{authComKey}")
    public Result<?> queryByCodeAndAuthComKey(
            @PathVariable("desformCode") String desformCode,
            @PathVariable("authComKey") String authComKey
    ) {
        return Result.ok(designFormAuthService.queryByCodeAndAuthComKey(desformCode, authComKey));
    }

    /**
     * 批量更新
     *
     * @param auths
     * @return
     */
    @PostMapping(value = "/updateBatch")
    public Result<?> updateBatch(@RequestBody List<DesignFormAuth> auths) {
        designFormAuthService.updateBatch(auths);
        return Result.ok("更新成功");
    }

    /**
     * 通过 comKey 删除
     *
     * @param auth
     * @return
     */
    @DeleteMapping(value = "/deleteByComKey")
    public Result<?> deleteByComKey(@RequestBody DesignFormAuth auth) {
        LambdaQueryWrapper<DesignFormAuth> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DesignFormAuth::getDesformCode, auth.getDesformCode());
        queryWrapper.eq(DesignFormAuth::getAuthComKey, auth.getAuthComKey());

        if (designFormAuthService.remove(queryWrapper)) {
            return Result.ok("删除成功!");
        } else {
            return Result.ok("条件不匹配");
        }
    }

    /**
     * 给字段添加权限
     *
     * @param auth
     * @return
     */
    @PostMapping(value = "/addAuth")
    public Result<?> addAuth(@RequestBody DesignFormAuth auth) {
        if (designFormAuthService.initialAuthInfo(auth)) {
            return Result.ok("添加成功！");
        } else {
            return Result.ok("添加失败！");
        }
    }

    /**
     * 编辑
     *
     * @param designFormAuth
     * @return
     */
    @PutMapping(value = "/edit")
    public Result<DesignFormAuth> edit(@RequestBody DesignFormAuth designFormAuth) {
        Result<DesignFormAuth> result = new Result<DesignFormAuth>();
        DesignFormAuth designFormAuthEntity = designFormAuthService.getById(designFormAuth.getId());
        if (designFormAuthEntity == null) {
            result.error500("未找到对应实体");
        } else {
            boolean ok = designFormAuthService.updateById(designFormAuth);
            if (ok) {
                result.success("修改成功!");
            }
        }

        return result;
    }

    /**
     * 批量保存或编辑（有 id 的编辑，否则就保存）
     *
     * @param authList
     * @return
     */
    @PutMapping(value = "/saveOrUpdateBatch")
    public Result saveOrUpdateBatch(@RequestBody List<DesignFormAuth> authList) {
        boolean ok = designFormAuthService.saveOrUpdateBatch(authList);
        if (ok) {
            return Result.ok("修改成功!");
        } else {
            return Result.ok("修改失败!");
        }
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        try {
            designFormAuthService.removeById(id);
        } catch (Exception e) {
            log.error("删除失败", e.getMessage());
            return Result.error("删除失败!");
        }
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @DeleteMapping(value = "/deleteBatch")
    public Result<DesignFormAuth> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        Result<DesignFormAuth> result = new Result<DesignFormAuth>();
        if (ids == null || "".equals(ids.trim())) {
            result.error500("参数不识别！");
        } else {
            this.designFormAuthService.removeByIds(Arrays.asList(ids.split(",")));
            result.success("删除成功!");
        }
        return result;
    }

    /**
     * 根据 authComKey 批量删除
     *
     * @param desformCode
     * @param authComKeys
     * @return
     */
    @DeleteMapping(value = "/deleteBatchByAuthComKey")
    public Result deleteBatchByAuthComKey(
            @RequestParam(name = "desformCode") String desformCode,
            @RequestParam(name = "authComKeys") String authComKeys
    ) {
        if (StringUtils.isEmpty(authComKeys)) {
            return Result.error("authComKeys 不能为空！");
        } else {
            LambdaQueryWrapper<DesignFormAuth> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(DesignFormAuth::getDesformCode, desformCode);
            queryWrapper.in(DesignFormAuth::getAuthComKey, Arrays.asList(authComKeys.split(",")));
            designFormAuthService.remove(queryWrapper);
            return Result.ok("删除成功!");
        }
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/queryById")
    public Result<DesignFormAuth> queryById(@RequestParam(name = "id", required = true) String id) {
        Result<DesignFormAuth> result = new Result<DesignFormAuth>();
        DesignFormAuth designFormAuth = designFormAuthService.getById(id);
        if (designFormAuth == null) {
            result.error500("未找到对应实体");
        } else {
            result.setResult(designFormAuth);
            result.setSuccess(true);
        }
        return result;
    }

    /**
     * 根据权限类型筛选 角色 授权数据
     *
     * @param designFormAuth
     * @param roleCode
     * @param permissionType
     * @param request
     * @return
     */
    @GetMapping(value = "/roleList/{roleCode}/{permissionType}/{desformCode}")
    public Result queryRolePageListByPermissionType(
            DesignFormAuth designFormAuth,
            @PathVariable("roleCode") String roleCode,
            @PathVariable("permissionType") String permissionType,
            @PathVariable("desformCode") String desformCode,
            HttpServletRequest request
    ) {
        String authScopeField = "auth_scope_roles_val";
        return designFormAuthService.buildResultByPermissionType(authScopeField, roleCode, designFormAuth, permissionType, desformCode, request);
    }

    /**
     * 根据权限类型筛选数据
     *
     * @param designFormAuth
     * @param permissionType
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @GetMapping(value = "/list/{permissionType}/{desformCode}")
    public Result queryPageListByPermissionType(
            DesignFormAuth designFormAuth,
            @PathVariable("permissionType") String permissionType,
            @PathVariable("desformCode") String desformCode,
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            HttpServletRequest req
    ) {
        PermissionTypeEnum perType = PermissionTypeEnum.getByValue(permissionType);
        if (perType != null) {
            QueryWrapper<DesignFormAuth> queryWrapper = QueryGenerator.initQueryWrapper(designFormAuth, req.getParameterMap());
            queryWrapper.eq("permission_type", permissionType);
            queryWrapper.eq("desform_code", desformCode);
            IPage<DesignFormAuth> pageList = designFormAuthService.pageList(pageNo, pageSize, queryWrapper);
            // 由于按钮有可能没有存到数据库，所以查出来的不一定是全部的数据，还需要合并一下
            if (perType == PermissionTypeEnum.BUTTON && StringUtils.isBlank(designFormAuth.getAuthField())) {
                List<DesignFormAuth> allDbList = pageList.getRecords();
                List<DesignFormAuth> allButtonList = DesformAuthUtils.getNewButtonList();
                List<DesignFormAuth> assignButtonList = DesformAuthUtils.assignButtonList(allButtonList, allDbList);
                pageList.setRecords(assignButtonList);
                pageList.setTotal(assignButtonList.size());
            }
            return Result.ok(pageList);
        } else {
            return Result.error("不识别的permissionType值");
        }
    }

    /**
     * 给字段添加权限
     *
     * @param auth
     * @return
     */
    @PostMapping(value = "/addAuth/{permissionType}")
    public Result addAuthByPermissionType(
            @RequestBody DesignFormAuth auth,
            @PathVariable("permissionType") String permissionType
    ) {
        if (designFormAuthService.addAuthByPermissionType(auth, permissionType)) {
            return Result.ok("添加成功！");
        } else {
            return Result.ok("添加失败！");
        }
    }

    /**
     * 编辑
     *
     * @param auth
     * @return
     */
    @PutMapping(value = "/edit/{permissionType}")
    public Result edit(@RequestBody DesignFormAuth auth,@PathVariable("permissionType") String permissionType) {
        if (designFormAuthService.editAuthByPermissionType(auth, permissionType)) {
            return Result.ok("添加成功！");
        } else {
            return Result.ok("添加失败！");
        }
    }

}
